package com.skywork.utils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

@MappedJdbcTypes(value = JdbcType.TINYINT, includeNullJdbcType = true)
public class MyEnumTypeHanlder extends BaseTypeHandler<MyEnum> {

	private Class<MyEnum> type;

	public MyEnumTypeHanlder() {
		System.out.print(this.getRawType());
		System.out.print("init");
	}

	public MyEnumTypeHanlder(Class<MyEnum> type) {
		if (type == null) {
			throw new IllegalArgumentException("Type argument cannot be null");
		}
		this.type = type;
	}

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, MyEnum parameter, JdbcType jdbcType) throws SQLException {
		ps.setInt(i, parameter.getValue());
	}

	@Override
	public MyEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return convert(rs.getInt(columnName));
	}

	@Override
	public MyEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return convert(rs.getInt(columnIndex));
	}

	@Override
	public MyEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return convert(cs.getInt(columnIndex));
	}

	private MyEnum convert(int status) {
		MyEnum[] objs = type.getEnumConstants();
		for (MyEnum em : objs) {
			if (em.getValue() == status) {
				return em;
			}
		}
		return null;
	}

}
